package cn.iluwen.airline.utils;

import jakarta.servlet.http.HttpServletRequest;

/**
 * HTTP请求工具类
 */
public class RequestUtils {
    
    /**
     * 获取用户的注册来源，基于User-Agent分析
     * @param request HTTP请求
     * @return 注册来源标识
     */
    public static String determineRegistrationSource(HttpServletRequest request) {
        String userAgent = request.getHeader("User-Agent");
        if (userAgent == null) {
            return "unknown";
        }
        
        userAgent = userAgent.toLowerCase();
        
        // 检测移动设备
        if (userAgent.contains("mobile") || userAgent.contains("android") || 
            userAgent.contains("iphone") || userAgent.contains("ipad")) {
            return "mobile";
        }
        
        // 检测常见浏览器
        if (userAgent.contains("msie") || userAgent.contains("trident")) {
            return "web-ie";
        } else if (userAgent.contains("chrome")) {
            return "web-chrome";
        } else if (userAgent.contains("firefox")) {
            return "web-firefox";
        } else if (userAgent.contains("safari")) {
            return "web-safari";
        }
        
        return "web"; // 默认为Web来源
    }
    
    /**
     * 获取客户端IP地址
     * @param request HTTP请求
     * @return IP地址
     */
    public static String getClientIp(HttpServletRequest request) {
        String ip = request.getHeader("X-Forwarded-For");
        
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        
        // 如果是多级代理，取第一个IP地址
        if (ip != null && ip.contains(",")) {
            ip = ip.split(",")[0].trim();
        }
        
        return ip != null ? ip : "0.0.0.0";
    }
} 